﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using USERS.CYT369.COM.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace USERS.CYT369.COM.Controllers
{
    public partial class UsersController
    {

        [HttpPost]
        public async Task<IActionResult> ChangeMyPassword()
        {
            var retVal = new USERS.CYT369.COM.Models.ExecuteResult();

            string oldPwd = Request.Form.GetString("OldPassword");
            string new1Pwd = Request.Form.GetString("New1Password");
            string new2Pwd = Request.Form.GetString("New2Password");
            if (string.Compare(new1Pwd, new2Pwd, false) == 0)
            {
                try
                {
                    var user = USERS.CYT369.COM.DAL.UserService.Instance.GetUserByID(this.GetUserId());
                    if (user != null)
                    {
                        var token = await m_UserManager.GeneratePasswordResetTokenAsync(user);
                        var result = await this.m_UserManager.ResetPasswordAsync(user, token, new1Pwd);
                        if (result.Succeeded)
                        {
                            retVal.Msg = "密码修改成功";
                            retVal.Result = true;
                        }
                        else
                        {
                            retVal.Msg = "密码修改失败";
                        }
                    }
                    else
                    {
                        retVal.Msg = "找不到登录账户";
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    retVal.Msg = "修改密码遭遇内部错误"+ex.Message;
#else
                    retVal.Msg = "修改密码遭遇内部错误";
#endif
                }
            }
            else
            {
                retVal.Msg = "两次输入的密码不一致";
            }

            return DefaultJson(retVal);
        }

    }
}
